package com.rjwh.dingdong.client.activity.community.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;

import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout.OnRefreshListener;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.community.CommunityPostDetailActivity;
import com.rjwh.dingdong.client.adapter.CommunityPostAdapter;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.bean.localbean.CommunityPostListBean;
import com.rjwh.dingdong.client.bean.localbean.ModularTab;
import com.rjwh.dingdong.client.bean.localbean.TagFilter;
import com.rjwh.dingdong.client.bean.localbean.TopicData;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.fragment.BaseFragment;
import com.rjwh.dingdong.client.mvp.presenter.impl.CommunityPostPresenter;
import com.rjwh.dingdong.client.mvp.view.CommunityPostView;
import com.rjwh.dingdong.client.view.TopicTagView;
import com.rjwh.dingdong.client.view.TopicTagView.OnTopicTagViewListener;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author 王小珂
 * @ClassName CommunityPostFragment
 * @Description 社区模块容器
 * @date 2016-3-28 下午4:27:10
 * @history 1.YYYY-MM-DD author: description:
 */
public class CommunityPostFragment extends BaseFragment implements OnTopicTagViewListener, CommunityPostView {
    @BindView(R.id.fragment_community_post_listview)
    ListView fragmentCommunityPostListview;
    @BindView(R.id.fragment_community_post_mPullRefreshView)
    SwipyRefreshLayout mSwipyRefreshLayout;
    LinearLayout tagviewrootView;

    private ModularTab modularTab;
    private CommunityPostAdapter adapter;
    private CommunityPostPresenter postPresenter;
    private int pageNumber = 0;
    private List<TagFilter> filters;
    private List<TopicTagView> listTagView = new ArrayList<>();
    private boolean isInit;


    public static CommunityPostFragment getInstance(ModularTab modularTab) {
        CommunityPostFragment communityPostFragment = new CommunityPostFragment();
        Bundle bd = new Bundle();
        bd.putSerializable("modularTab", modularTab);
        communityPostFragment.setArguments(bd);
        return communityPostFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.community_post_layout, container, false);
        View headView = inflater.inflate(R.layout.community_post_headview, null);
        ButterKnife.bind(this, rootView);
        initView(headView);
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            modularTab = (ModularTab) getArguments().getSerializable("modularTab");
            assert modularTab != null;
            filters = modularTab.getFilters();
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        postPresenter = new CommunityPostPresenter(getActivity(), this);
        if (getUserVisibleHint() && isVisible() && isInit) {
            mSwipyRefreshLayout.doPullRefreshing();//加载数据的方法
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        //判断Fragment中的ListView时候存在，判断该Fragment时候已经正在前台显示  通过这两个判断，就可以知道什么时候去加载数据了
        if (isVisibleToUser && isVisible() && isInit) {
            mSwipyRefreshLayout.doPullRefreshing();//加载数据的方法
        } else {
            isInit = false;
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isInit = true;//初始化后 将其设置成true  表示已经初始化控件过了
    }

    private void initView(View headView) {
        tagviewrootView = (LinearLayout) headView.findViewById(R.id.fragment_community_post_header_tagview_root_ll);
        mSwipyRefreshLayout.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh(SwipyRefreshLayoutDirection direction) {
                switch (direction) {
                    case TOP:
                        pageNumber = 0;
                        doGetTopicList(true, SwipyRefreshLayoutDirection.TOP);
                        break;

                    case BOTTOM:
                        pageNumber++;
                        doGetTopicList(false, SwipyRefreshLayoutDirection.BOTTOM);
                        break;

                    default:
                        break;
                }
            }
        });
        fragmentCommunityPostListview.addHeaderView(headView);

        adapter = new CommunityPostAdapter(getActivity());
        fragmentCommunityPostListview.setAdapter(adapter);
        fragmentCommunityPostListview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CommunityPostListBean item = (CommunityPostListBean) parent.getAdapter().getItem(position);
                if (item == null) {
                    return;
                }
                int type = item.getType();
                if (type == 1) {
                    TopicData topicItem = (TopicData) item.getObject();

                    String filepath = topicItem.getFilepath();
                    Intent intent = new Intent(getActivity(), CommunityPostDetailActivity.class);
                    if (topicItem.getTopicid() != null) {
                        intent.putExtra("topicid", topicItem.getTopicid());
                    }
                    if (filepath != null) {
                        String userid = MyApplication.spUtil.getStrPreferenceByParamName(getContext(), LocalConstant.SP_USERID);
                        String babyid = MyApplication.spUtil.getStrPreferenceByParamName(getContext(), LocalConstant.SP_BABYID);
                        String version = MyApplication.versionCode;
                        String uuid = MyApplication.deviceId;
                        String token = MyApplication.spUtil.getStrPreferenceByParamName(getContext(), LocalConstant.SP_USER_TOKEN);
                        String url = filepath + String.format(LocalConstant.URL_BASE, userid, babyid, version, uuid, token);
                        intent.putExtra("url", url);
                    }
                    startActivity(intent);
                }
            }
        });
        if (filters != null) {
            for (int i = 0; i < filters.size(); i++) {
                addTagView(filters.get(i));
            }
        }

    }

    @Override
    public void setTagCheck(TopicTagView view) {
        mSwipyRefreshLayout.doPullRefreshing();
    }

    public void doGetTopicList(boolean isRefresh, SwipyRefreshLayoutDirection direction) {
        JSONArray arrayFilert = new JSONArray();
        for (int i = 0, j = listTagView.size(); i < j; i++) {
            TopicTagView tagView = listTagView.get(i);
            arrayFilert.put(tagView.getFilert());
        }
        postPresenter.doGetTopicList(modularTab.getId(), pageNumber, arrayFilert.toString(), isRefresh, direction);
    }

    @Override
    public void setDirection(SwipyRefreshLayoutDirection direction) {
        mSwipyRefreshLayout.setDirection(direction);
    }

    @Override
    public void setRefreshing(boolean refreshing) {
        mSwipyRefreshLayout.setRefreshing(refreshing);
    }

    @Override
    public void loadData(boolean isRefresh, List<CommunityPostListBean> data) {
        if (isRefresh) {
            adapter.clear();
        }
        adapter.appendToList(data);
    }

    /**
     * 添加tag视图
     *
     * @param tagFilter 标签
     */
    private void addTagView(TagFilter tagFilter) {
        TopicTagView tagLayout = new TopicTagView(getActivity());
        tagLayout.setOnTopicTagViewListener(this);
        tagLayout.setTagData(tagFilter, true);
        float density = getResources().getDisplayMetrics().density;
        LayoutParams params_rb = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        int margin = (int) (2 * density);
        params_rb.setMargins(0, margin, 0, margin);
        tagviewrootView.addView(tagLayout, params_rb);
        listTagView.add(tagLayout);
    }

    @Override
    public void onDestroy() {
        postPresenter.detachView();
        super.onDestroy();
    }

}
